package com.atguigu.gulimall.cart.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate  redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PZREFIX="gulimall:cart:";
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> boundHashOperations = getOperations();
        //判断购物车里是否有商品
        String res = (String) boundHashOperations.get(skuId.toString());
        if (StringUtils.isEmpty(res)){
            //没有就要执行添加
            //给购物车添加新商品
            CartItem cartItem = new CartItem();
            /**
             * 使用线程池
             * 1）导入线程池的配置文件,ThreadPoolConfig,ThreadPoolConfigProperties
             * 2）依赖注入 ThreadPoolExecutor executor
             * 3）使用CompletableFuture来选择对应的多线程方式
             */
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                //1.远程查询要添加的商品信息
                R skuInfo = productFeignService.info(skuId);
                SkuInfoVo skuInfoEntity = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //2.将商品添加到购物车

                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfoEntity.getSkuDefaultImg());
                cartItem.setTitle(skuInfoEntity.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfoEntity.getPrice());
            },executor);

            //3.远程查询sku的组合信息,获取销售属性
            CompletableFuture<Void> getSaleAttr = CompletableFuture.runAsync(() -> {
                List<String> saleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(saleAttrValues);
            },executor);

            CompletableFuture.allOf(getSkuInfo,getSaleAttr).get();
            //4.将获取到的数据放到redis中
            String cartJsonStr = JSON.toJSONString(cartItem);
            boundHashOperations.put(skuId.toString(),cartJsonStr);
            return cartItem;
        } else {
            //购物车有这个商品,修改购物车的数量
            CartItem redisCartItem = JSON.parseObject(res, CartItem.class);
            redisCartItem.setCount(redisCartItem.getCount()+num);

            boundHashOperations.put(skuId.toString(),JSON.toJSONString(redisCartItem));
            return redisCartItem;
        }
    }



    /**
     * 获取到我们要操作到的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getOperations() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //1.购物车使用临时还是用户登录
        String cartKey="";
        if(userInfoTo.getUserId()!=null){
            //登陆了的存储到redis中的key例如：gulimall:cart:1
            cartKey=CART_PZREFIX+userInfoTo.getUserId();
        }else{
            cartKey=CART_PZREFIX+userInfoTo.getUserKey();
        }

        //2.操作添加购物车
        BoundHashOperations<String, Object, Object> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        return boundHashOperations;
    }

    /**
     * 跳转到成功页
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getOperations();
        String s = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(s, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        //1.区分登录和不登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() !=null){
            //1.登录,还要将没登录的购物车进行合并
            String cartKey = CART_PZREFIX+userInfoTo.getUserId();
            String tempCartKey = CART_PZREFIX+userInfoTo.getUserKey();
            //2.获取临时购物车的购物项,看是否有购物项
            List<CartItem> tempItems = getCartItems(tempCartKey);
            if(tempItems !=null){
                //临时购物车有数据需要合并
                for (CartItem tempItem : tempItems) {
                    addToCart(tempItem.getSkuId(), tempItem.getCount());
                }
                //合并完毕后清除临时购物车的数据
                clearCartItems(tempCartKey);
            }
            //3.获取最终登录后的购物车[包含合并的临时购物车]
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }else {
            //没登录
            String cartKey =CART_PZREFIX+ userInfoTo.getUserKey();
            //获取临时购物车所有的购物项
            cart.setItems(getCartItems(cartKey));
        }
        return cart;
    }

    /**
     * 获取购物车里的购物项
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOperations.values();

        if (values !=null && values.size()>0){
            List<CartItem> cartItems = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItems;
        }
        return null;
    }

    @Override
    public void clearCartItems(String cartKey){
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer checkNum) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(checkNum==1?true:false);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> operations = getOperations();
        operations.put(skuId.toString(),s);
    }

    @Override
    public void countItem(Long skuId, Integer changeNum) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(changeNum);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> operations = getOperations();
        operations.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getOperations();
        operations.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()==null){
            return null;
        }else {
            String cartKey = CART_PZREFIX+userInfoTo.getUserId();
            //获取所有的被选中的购物项
            List<CartItem> cartItems = getCartItems(cartKey).stream().map(item->{
                //更新最新的价格
                item.setPrice(productFeignService.getPrice(item.getSkuId()));
                return item;
            }).filter(item -> item.getCheck()).collect(Collectors.toList());
            return  cartItems;
        }
    }
}
